#!/usr/local/bin/python
# coding: latin-1

# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from django import get_version
from subfactory.models import Document
from subfactory.models import DocumentVersion
from subfactory.forms import DocumentForm
from subfactory.forms import UploadFileForm
from django.utils import timezone
from subfactory.tools.tools import DocumentContainer
from subfactory.tools.tools import Difference
from subfactory.tools.tools import DocumentFormatter
import logging
from django.template.loader import render_to_string

logger = logging.getLogger('views')

def index(request):
	document_list = Document.objects.order_by('-creation_date')
	django_version = get_version()
	context = {'document_list': document_list,
		 'django_version': django_version,
		}
	return render(request, 'subfactory/index.html', context)



def document(request, document_id):
	document = get_object_or_404(Document, id=document_id)
	version_list = DocumentVersion.objects.filter(document=document).order_by('-creation_date')
	last_version = version_list[0]
	context = {
		'document': DocumentContainer.parse(document.content), 
		'version_list': version_list, 
		'last_version':last_version,
		'version':last_version,
		'document_id':document.id
	}
	return render(request, 'subfactory/document.html', context)

def version(request, version_id):
	version = get_object_or_404(DocumentVersion, id=version_id)
	version_list = DocumentVersion.objects.filter(document=version.document).order_by('-creation_date')
	last_version = version_list[0]
	context = {
		'document': DocumentContainer.parse(version.content), 
		'version_list': version_list, 
		'last_version':last_version,
		'version':version,
		'document_id':version.document.id
	}
	return render(request, 'subfactory/document.html', context)

def document_add(request):
	form = DocumentForm()
	return render(request, 'subfactory/document_add.html', {'form': form})

def document_change(request, document_id):

	document = get_object_or_404(Document, id=document_id)
	data = {
		'title': document.title,
	        'content': document.content,
	}
	form = DocumentForm(data)
	return render(request, 'subfactory/document_edit.html', {'form': form, 
								 'document_id' : document_id, 
								 'document' : DocumentContainer.parse(document.content)
	})

def document_save(request, document_id):
	form = DocumentForm(request.POST)
	#form_title = form.cleaned_data['title']
	#form_content = form.cleaned_data['content']
	today = timezone.now()
	doc = get_object_or_404(Document, id=document_id)
	version = doc.version + 1
	doc.version = version
	#doc.title = form_title
	container = DocumentContainer.parse(doc.content)
	for line in container.lines:
		line.traduction = request.POST['traduction_'+str(line.number)]
	doc.content = container.render()

	doc.save()
	documentVersion = DocumentVersion(title=doc.title,
				  content=doc.content,
				  creation_date=today,
					  version=version,
					  comment="Création du document",
					  document=doc)
	documentVersion.save()
	return document(request, doc.id)

def difference(request,first_version_id, second_version_id):
	first_version = get_object_or_404(DocumentVersion, id=first_version_id)
	second_version = get_object_or_404(DocumentVersion, id=second_version_id)
	first_container=DocumentContainer.parse(first_version.content)
	second_container=DocumentContainer.parse(second_version.content)
	differences=[]
	i = 0
	while i < len(first_container.lines):
		first_line = first_container.lines[i]
		second_line = second_container.lines[i]
		difference = Difference(first_line, second_line)
		differences.append(difference)
		i += 1
		
	return render(request, 'subfactory/difference.html', {'differences': differences, 'document_id': first_version.document.id})

def upload_file(request):
	if request.method == 'POST':
		form = UploadFileForm(request.POST, request.FILES)
		if form.is_valid():
			uploaded_file = request.FILES['file']
			file_title = uploaded_file.name
			file_content = uploaded_file.read()
			save_new_document(file_title, file_content)
			return index(request)
	form = UploadFileForm()
	return render(request, 'subfactory/upload.html', {'form': form})

def save_new_document(title, content):
	today = timezone.now()
	doc = Document(
		title=title,
		content=content,
		creation_date=today,
		version=1
		)
	formatter = DocumentFormatter()
	formatter.format(doc)

	doc.save()
	documentVersion = DocumentVersion(title=doc.title,
				  content=doc.content,
				  creation_date=today,
				  version=doc.version,
				  comment="Création du document",
				  document=doc)
	documentVersion.save()
	
def download_translation(request, version_id):
	version = get_object_or_404(DocumentVersion, id=version_id)
	#logger.info(document.content)
	content = render_to_string("subfactory/format/out.srt", {'document' : DocumentContainer.parse(version.content)})
	#logger.info(content)
	response = HttpResponse(content, content_type='application/srt')
	response['Content-Disposition'] = 'attachment; filename=translation.srt'
	return response
	
